﻿namespace ETestIT.UI
{
    using System;
    using System.Web.UI.WebControls;
    using Core;
    using Core.DataInterfaces;
    using Core.Infrastructure;
    using Presentation;
    using Presentation.Storage;

    public partial class Users : PageBase<Users>
    {
        private const string EditeduserKey = "editedUser";

        private ISessionProvider sessionStorage;
        private IUserRepository userRepository;

        protected void Page_Load(object sender, EventArgs e)
        {
            userAddEdit.Update += UserAddEditUpdate;
            
            userRepository = IoC.Resolve<IUserRepository>();
            sessionStorage = IoC.Resolve<ISessionProvider>();
            
            if (!IsPostBack)
                GetAllCandidates();
        }

        private void GetAllCandidates()
        {
            gvUsers.DataSource = userRepository.GetAll();
            gvUsers.DataBind();
        }

        protected void LnkEditCommand(object sender, CommandEventArgs e)
        {
            var userId = int.Parse(e.CommandArgument.ToString());
            var user = userRepository.Get(userId);

            switch (e.CommandName)
            {
                case "UserEdit":
                    {
                        userAddEdit.SetModel(user);
                        userAddEdit.Visible = Visible;
                        sessionStorage.Set(EditeduserKey, userId);
                        GetAllCandidates();
                        break;
                    }
                case "UserDelete":
                    {
                        With.Transaction(()=>
                            userRepository.Delete(user));
                        GetAllCandidates();
                        break;
                    }
                default:
                    userAddEdit.Visible = false;
                    break;
            }
        }

        protected void BtnCreateNewUser_Clicked(object sender, EventArgs e)
        {
            userAddEdit.Visible = Visible;
        }

        public void UserAddEditUpdate(object sender, EventArgs e)
        {
            var theUser = 
                sessionStorage.Contains(EditeduserKey) ? 
                userRepository.Get(sessionStorage.Get<int>(EditeduserKey)) : 
                new User();

            if (userAddEdit.IsInputValide())
            {
                userAddEdit.UpdateModelFromUserInput(theUser);
                
                With.Transaction(()=> 
                    userRepository.SaveOrUpdate(theUser));

                userAddEdit.Visible = false;
                GetAllCandidates();

                if (sessionStorage.Contains(EditeduserKey))
                    sessionStorage.Remove(EditeduserKey);
            }
        }
    }
}